define(["jquery","bbcare",
	"scprit/nutrition/app/nutritionApplication/addNutritionScheme.servers.js",
	"scprit/nutrition/app/nutritionApplication/addNutritionScheme.ui.js"],
	function($,$bb,$servers,$ui){
	var event = {};

	/**
	 * 搜索成功后点击选中某个患者
	 */
	var onPatientSelect = function(){
		var rows = $(this).data("rows");
		var index = $(this).index();
		$("#patientsList").hide();
		$ui.infoInit({
			"id":"infoBox",
			"data":rows[index]
		});
	}

	/**
	 * 请求患者列表成功后的回调函数
	 */
	var ajaxPatientsCallBack = function(data){
		if(data.rows && data.rows.length > 0){
			$ui.patientsInit({
				"id":"patientsList",
				"list":data.rows
			});
			$("#patientsList").show();
			$("#patientsList li").unbind("click");
			$("#patientsList li").data({"rows":data.rows});
			$("#patientsList li").click(onPatientSelect);
		}else{
			$("#patientsList").html('<div class="null">未找到该患者，请核对查询信息或者为该患者建档</div>');
			$("#patientsList").show();
		}
	}

	/**
	 * 根据手机号和姓名搜索患者
	 */
	event.onSearchPatient = function(){
		var value = $(this).val();
		if(value != ""){
			var params = {
				"flag":2,
				"fuzzyVar":value,
				"systemType":"02"
			}
			var reg = /^1\d{10}$/;
			if( reg.test(value) ) $.extend(params,{"phoneNum":value});
			$servers.ajaxPatients(params,ajaxPatientsCallBack);
		}else{
			$("#patientsList").hide();
		}
	}

	/**
	 * 清空搜索框内的内容
	 */
	event.onEmptyClick = function(){
		$(this).parent().find("input").val("");
		$("#patientsList").hide();
	}

	/**
	 * 启用方案成功后，跳转到详情页
	 */
	var ajaxSchemeUsedCallBack = function(data,userId){
		$bb.toastShow("成功启用了该方案");
		var params = {
			"ptSchemeId":data.ptNtschemeId,
			"userId":userId
		};
		$bb.openPage("nutritionApplicationDetails",{"value":params});
	}

	/**
	 * 点击保存
	 */
	event.onSubmit = function(){
		if( $("#infoBox .info-name").length > 0 ){
			var schemeVersionId = $("#selectNutritionScheme").val();
			if(schemeVersionId != ""){
				var userId = $("#infoBox .info-name").attr("patientId");
				var params = {
					"schemeVersionId":schemeVersionId,	
				    "useType":"2",
				    "userId":userId
				};
				$servers.ajaxSchemeUsed(params,ajaxSchemeUsedCallBack);
			}else{
				$bb.toastShow("请先发布该方案！");
			}
		}else{
			$bb.toastShow("请先搜索患者并选中患者！");
		}
	}

	return event;
});